<!-- 平台匹配组件 -->
<template>
  <div class="d-flex">
    <div class="flex-1 cell">{{ title }}</div>
    <!-- 匹配小区 -->
    <div class="flex-1 cell" v-loading="portVO.loading">
      <div v-show="!portVO.portResblockName && !portVO.loading" class="text-red">
        未匹配
      </div>
      <div v-show="portVO.portResblockName && !portVO.loading">
        {{ portVO.portResblockName }}
      </div>
    </div>

    <!-- 匹配 户室号 -->
    <div class="flex-3 cell" v-loading="portVO.hallRoomLoading">
      <div
        v-show="!portVO.hallRoomLoading && portVO.hallRoomNumber.length == 0 && portVO.portResblockName"
        style="margin: auto"
        class="fs-sm text-center"
      >
        加载失败,
        <el-button type="text" @click="handleRetryColumn">点击重试</el-button>
      </div>
      <div class="d-flex">
        <template v-for="item in portVO.hallRoomNumber">
          <!-- 分两种情况 一种是自定义输入 另一种只能点选 -->
          <el-input 
            v-if="portVO.huShiHao" 
            v-model="portVO[item.key]" 
            :key="item.key" 
            style="margin: 0 5px" 
            :class="{ 'reject-input': !portVO[item.key] }"
            :placeholder="item.title"
          ></el-input>
          <el-select
            v-else
            v-model="portVO[item.key]"
            filterable
            remote
            :allow-create="portVO.huShiHao"
            :placeholder="item.title"
            :key="item.key"
            :loading="portVO.singleLoading"
            :disabled="selectDisabled(item.key)"
            :remote-method="remoteMethod(item.key)"
            @focus="handleFocusHsh('portVO', item.key)"
            @change="handleChangeHsh('portVO', $event)"
            style="margin: 0 5px"
            :class="{ 'reject-input': !portVO[item.key] }"
          >
            <el-option
              v-for="item in portVO.buildUnitDoorOptions"
              :label="item.portBuild || item.portUnit || item.portDoorNum"
              :value="item.platformBuildId || item.platformUnitId || item.platformDoorNumId"
              :key="item.platformBuildId || item.platformUnitId || item.platformDoorNumId"
            ></el-option>
          </el-select>
        </template>
      </div>
      <div :class="[hushihaoFilledPrue ? 'text-green' : 'text-red', 'text-center']">
        {{hshTips}}
      </div>
    </div>

    <!-- 总价 -->
    <div
      class="flex-1 cell"
      v-loading.fullscreen="portVO.isCheckingPrice"
      element-loading-text="价格校验中..."
      element-loading-background="rgba(0, 0, 0, 0.8)"
    >
      <el-input
        v-show="hushihaoFilled && !isResetPriceBuildSize"
        v-model="myTotalPrices"
        :class="{
          'reject-input': portVO.totalPricesIgnore ? false : !portVO.totalPricesPassed,
        }"
        :disabled="!portVO.portResblockName || !portVO.platformResblockId"
      >
        <i slot="suffix" style="font-style: normal">万元/套</i>
      </el-input>
      <div
        v-show="myTotalPrices && hushihaoFilled && !isResetPriceBuildSize"
        :class="['text-center', portVO.totalPricesPassed ? 'text-green' : 'text-red']"
      >
        {{ priceTips }}
      </div>
    </div>
    <!-- 面积 -->
    <div class="flex-1 cell" v-loading="portVO.isMatchingBuild" element-loading-text="面积匹配中...">
      <el-input
        v-show="hushihaoFilled"
        v-model="myBuildSize"
        :readonly="portVO.buildSizeLocked"
        :disabled="!portVO.portResblockName || !portVO.platformResblockId"
      >
        <i slot="suffix" style="font-style: normal">平方米</i>
      </el-input>
      <div v-show="hushihaoFilled && portVO.buildSizeLocked" class="text-center text-green">面积已锁定</div>
    </div>
    <!-- 均价 -->
    <div class="flex-1 cell">{{averagePrice}}</div>
    <!-- 操作 -->
    <div class="flex-1 cell">
      <el-button size="mini" type="text" @click="handlePopShow">{{
        portVO.portResblockName ? "重新匹配小区" : "手工匹配小区"
      }}</el-button>
    </div>

    <!-- 手动匹配弹层 -->
    <el-dialog :visible.sync="popVisible" top="30vh" :close-on-click-modal="false" :show-close="true" width="600px" append-to-body>
      <span slot="title" class="d-flex ai-baseline">
        <span class="fs-xl" style="margin-left: 8px">手工匹配</span>
        <span>（注：输入小区或关键字后，需点击“搜索”按钮）</span>
      </span>
      <comManualMatch :popModel="popModel" :delId="delId"></comManualMatch>
      <span slot="footer" class="dialog-footer">
        <el-button plain @click="popVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePopConfirm">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import comTitleItem from "@/views/house/com/com-title-item";
import comManualMatch from "@/views/house/com/com-manual-match";
import { hallRoomNumber } from "@/config/house/houseDetailConfig";
import platform from "@/config/house/platform";
import {
  matchingResblock,
  matchingBuild,
  matchingUnit,
  matchinDoorNum,
  checkPrice,
} from "@/api/user";
import { asyncTimeoutHandler, debounce, smoothAsyncHandler } from "@/utils/utilsNew";

let needlessPriceCheck = false
export default {
  name: 'ComMatchItem',
  components: {
    comTitleItem,
    comManualMatch,
  },
  props: {
    model: {
      type: Object,
      default() {
        return {};
      }
    },
    resblockName: {
      type: String,
      default: "",
    },
    noPortAccount: {
      type: Number,
      default: 0,
    },
    delId: String
  },
  data() {
    return {
      isResetPriceBuildSize: true, //是否重置了总价和面积，重置了则不展示总价
      myTotalPrices: "",
      myBuildSize: "",
      handleTimer: null,
      intervalTime: 2000,
      totalTimes: 0,
      tryTimes: 0,
      popVisible: false,
      title: "",

      // 暂且只用了匹配小区相关数据
      popModel: {
        portResblockName: "", //端口小区名称
        portResblockId: "",

        platformResblockId: "", //平台小区id
        platformBuildId: "", //平台楼栋id
        platformUnitId: "", //平台单元ID
        platformDoorNumId: "", //平台门牌号ID

        portType: "", // 平台类型
        loading: false, //匹配小区加载
        searchKey: "", //搜索关键词

        housingEstateOptions: [], //匹配小区选项
      },
      // 端口信息
      portVO: {
        portResblockName: "", //端口小区名称
        portBuild: "", //栋/幢
        portUnit: "", //单元/号
        portDoorNum: "", //门牌

        // portResblockId: "", //不用的id系列
        // portBuildId: "",
        // portUnitId: "",
        // portDoorNumId: "",
        
        platformResblockId: "", //平台小区id   (platform 代表安居客等平台)
        platformBuildId: "", //平台楼栋id
        platformUnitId: "", //平台单元ID
        platformDoorNumId: "", //平台门牌号ID

        portType: "", // 平台类型
        loading: false, //匹配小区加载。。。
        hallRoomLoading: false, //户室号加载。。。
        singleLoading: false, //单个户室号加载。。。
        isCheckingPrice: false, //校验价格中。。。
        isMatchingBuild: false, //匹配面积中。。。
        searchKey: "", //搜索关键词
        hallRoomNumber,

        housingEstateOptions: [], //匹配小区选项
        buildUnitDoorOptions: [], //户室号的选项
        huShiHao: false, //是否支持手动输入
        buildSizeLocked: false, //是否建筑面积锁定
        totalPricesPassed: false, //是否总价通过校验
        totalPricesTimeout: false, //是否总价超时
        totalPricesIgnore: false, //是否总价忽略校验

        totalPrice: "",
        buildingSize: "",
      },
    };
  },

  created() {
    // console.log('组件', this);
    
    this.fetchCheckPrice = debounce(this.fetchCheckPrice.bind(this), 1500);
  },

  mounted() {
    // 历史问题 此处需要优化 (首次进来会触发价格校验)
    if (this.model.onePushFlag == 0) {
      needlessPriceCheck = true
    }
    this.myTotalPrices = this.model.totalPrice
    this.myBuildSize = this.model.buildingSize
    this.renderPort(this.model, this.resblockName);
    this.title = platform[this.portVO.portType];

    this.popModel.portType = this.portVO.portType;
  },

  computed: {
    // 户室号匹配文案
    hshTips() {
      if (!this.portVO.portResblockName) return "(未匹配)"
      if (this.hushihaoFilledPrue) return "(已匹配)";
      return `(未匹配 - ${this.portVO.huShiHao? '请输入户室号' : '请选择户室号'})`
    },
    averagePrice() {
      if (!this.hushihaoFilled) return ""
      if (!this.myTotalPrices || !this.myBuildSize) return ""
      const p = (this.myTotalPrices / this.myBuildSize).toFixed(2) + '万'
      return p
    },
    priceTips() {
      if (this.portVO.totalPricesIgnore) return "";
      if (this.portVO.totalPricesPassed) return "价格校验通过";
      if (this.portVO.totalPricesTimeout) return "价格校验超时，请重试";
      return "价格远超该房源市场价，请修改";
    },

    // 户室号是否匹配ok (如果支持手输huShiHao则跳过校验)
    hushihaoFilled() {
      let info = this.portVO;
      if (!info.portResblockName) return false;
      
      if (info.huShiHao) return true;
      if (!info.hallRoomNumber || info.hallRoomNumber.length == 0) {
        return false;
      }
      const protFilledList = hallRoomNumber.map((v) => v.key).filter((key) => this.isValidValue(info[key]));
      let r = protFilledList.length >= info.hallRoomNumber.length;
      return r;
    },

    // 纯 户室号有没有填
    hushihaoFilledPrue() {
      let info = this.portVO;
      if (!info.portResblockName) return false;
      if (!info.hallRoomNumber || info.hallRoomNumber.length == 0) {
        return false;
      }
      const protFilledList = hallRoomNumber.map((v) => v.key).filter((key) => this.isValidValue(info[key]));
      let r = protFilledList.length >= info.hallRoomNumber.length;
      return r;
    },

    selectDisabled() {
      return (key) => {
        if (this.portVO.hallRoomNumber.length == 0) {
          return true;
        }
        if (!this.portVO.portResblockName) return true;

        let hasBuild = this.portVO.hallRoomNumber.find((v) => v.key == "portBuild");
        let hasUnit = this.portVO.hallRoomNumber.find((v) => v.key == "portUnit");

        if (key == "portUnit") {
          if (hasBuild && !this.portVO.portBuild) return true;
          return false;
        }
        if (key == "portDoorNum") {
          if (hasBuild && !this.portVO.portBuild) return true;
          if (hasUnit && !this.portVO.portUnit) return true;
          return false;
        }
      };
    },
  },

  watch: {
    portVO: {
      handler(newVal, oldVal) {
        this.$emit("updateportvo", newVal);
      },
      deep: true,
    },

    myBuildSize(newValue, oldValue) {
      if (newValue == oldValue) return ;
      this.portVO.buildingSize = newValue
      this.fetchCheckPrice();
    },

    myTotalPrices(newValue, oldValue) {
      if (newValue == oldValue) return;
      this.portVO.totalPrice = newValue
      this.fetchCheckPrice();
    },
  },

  beforeDestroy() {
    if (this.handleTimer) {
      clearTimeout(this.handleTimer);
      this.handleTimer = null;
    }
  },

  methods: {
    renderPort(data, resblockName) {
      Object.assign(this.portVO, data);

      // console.log('this.portVO== ', this.portVO)

      if (this.portVO.totalPricesPassed) {
        this.$emit("ontotalpricespassed", true);
      }
      if (this.portVO.totalPricesIgnore) {
        this.$emit("ontotalpricesignore", true);
      }

      // 可推表示填写完整了
      if (data.onePushFlag == 0) {
        this.portVO.hallRoomNumber = hallRoomNumber.filter((v) => !!data[v.key]);

        this.isResetPriceBuildSize = false;
      } else {
        this.resetHuShiHao("portVO");

        // 已匹配过小区
        if (data.portResblockName) {
          this.getHshColumn("portVO", data);

          // 自动帮他匹配小区
        } else {
          if (this.noPortAccount == 1) {
            this.portVO.hallRoomNumber = [];
            this.autoMatchingResblock("portVO", resblockName);
          }
        }
      }
    },

    // 更新为推荐的户室号
    updateRecommendHushihao(info) {
      if (
        this.portVO.loading ||
        this.portVO.hallRoomLoading ||
        this.portVO.singleLoading ||
        this.portVO.isCheckingPrice ||
        this.portVO.isMatchingBuild
      ) {
        return this.$message.error('加载中，请稍后再试~');
      }
      // console.log("更新为推荐的户室号，", info);

      const keys = ["buildingName", "buildingUnitName", "houseName"];
      const arr = hallRoomNumber.filter((item, i) => info[keys[i]]);
      this.portVO.hallRoomNumber = arr;
      this.portVO.huShiHao = false;

      this.portVO.platformBuildId = info.buildingId;
      this.portVO.platformUnitId = info.buildingUnitId;
      this.portVO.platformDoorNumId = info.houseId;

      this.portVO.portDoorNumId = info.houseId;

      this.portVO.portBuild = info.buildingName;
      this.portVO.portUnit = info.buildingUnitName;
      this.portVO.portDoorNum = info.houseName;

      this.myBuildSize = info.buildingArea;
      // 强制校验以免面积不变情况
      this.fetchCheckPrice();
      
      this.portVO.buildSizeLocked = info.buildingAreaLock == "0";
    },

    // 校验价格是否合格
    fetchCheckPrice() {
      if (needlessPriceCheck) {
        needlessPriceCheck = false
        return
      }
      if (!this.hushihaoFilled) return;
      const { myTotalPrices: totalPrices, myBuildSize: buildSize } = this;
      // console.log({totalPrices, buildSize});

      if (!totalPrices || !buildSize) {
        this.isResetPriceBuildSize = false;
        this.portVO.isCheckingPrice = false;
        return;
      }

      if (!this.portVO.isCheckingPrice) {
        this.portVO.isCheckingPrice = true;
      }

      asyncTimeoutHandler(
        checkPrice({
          platformResblockId: this.portVO.platformResblockId,
          platformDoorNumId: this.portVO.platformDoorNumId,
          portType: this.portVO.portType,
          totalPrices,
          buildSize,
        })
      )
        .then(({ isSuccess, content = "", errorCode, errorMessage }) => {
          this.portVO.isCheckingPrice = false;
          this.isResetPriceBuildSize = false;
          this.portVO.totalPricesTimeout = false;

          if (!isSuccess && errorCode=='account_login.name_or_pass_fail'){
            this.$alert('系统检测到您在58安居客的账号密码发生了修改，请修改最新的密码重新绑定后进行使用~', '', {
              confirmButtonText: '重新绑定账号',
              callback: action => {
                this.$router.push({ name: "portManagement" });
              }
            });
            return
          }
          else if (!isSuccess && errorCode=='account_login.check_mobile'){
            this.$alert('系统检测到您在58安居客的账号需要短信验证，验证完即可使用~', '', {

              confirmButtonText: '立即验证',
              callback: action => {
                this.$router.push({ name: "portManagement" });
              }
            });
            return
          }
          if (!isSuccess || !content) {
            this.portVO.totalPricesIgnore = true;
            this.$emit("ontotalpricesignore", true);
            return;
          }

          this.portVO.totalPricesPassed = JSON.parse(content);
          this.$emit("ontotalpricespassed", this.portVO.totalPricesPassed);
          this.portVO.totalPricesIgnore = false;
          this.$emit("ontotalpricesignore", false);
        })
        .catch(() => {
          this.portVO.isCheckingPrice = false;
          this.isResetPriceBuildSize = false;
          this.portVO.totalPricesTimeout = true;
          this.portVO.totalPricesPassed = false;
          this.portVO.totalPricesIgnore = false;
          // console.log("校验超时了");
        });
    },
    // 自动匹配小区
    autoMatchingResblock(way, name) {
      const m = this[way]
      m.loading = true;
      matchingResblock({
        delId: this.delId,
        portResblockName: (name || '').trim(),
        portType: m.portType,
        actionType: way == "portVO" ? 0 : 1,
        type: 0,
      }).then((content) => {
        this.tryTimes = 0;
        m.loading = false;

        if (content.length) {
          m.housingEstateOptions = content;
          if (way == "portVO") {
            this.handleChangePortResblockName(way, content[0].portResblockName);
          }
        }
      }).catch(() => {
        let setSuccess = this.setTimer(() => {
          this.autoMatchingResblock(way, name);
          console.log("重新匹配。。。");
        });
        if (!setSuccess) {
          m.loading = false;
        }
      });
    },

    setTimer(fn) {
      if (this.tryTimes >= this.totalTimes) {
        this.tryTimes = 0;
        return false;
      }
      this.tryTimes = this.tryTimes + 1;
      if (this.handleTimer) {
        clearTimeout(this.handleTimer);
        this.handleTimer = null;
      }
      this.handleTimer = setTimeout(fn, this.intervalTime);
      return true;
    },

    // 匹配到小区
    handleChangePortResblockName(way, value) {
      const m = this[way]
      const item = m.housingEstateOptions.find((v) => v.portResblockName == value);
      Object.assign(m, item);

      if (way == "portVO") {
        this.getHshColumn(way, item);
      }
    },

    handleFocusHsh(way, key, kw = "") {
      const m = this[way]
      if (m.huShiHao) return

      m.singleLoading = true;
      m.buildUnitDoorOptions = [];
      const ct = () => {
        // 需要尝试重新请求
        m.singleLoading = false;
      }

      const cb = (content) => {
        this.tryTimes = 0;
        m.singleLoading = false;

        if (content.length) {
          m.buildUnitDoorOptions = content;
        }
      };

      if (key == "portBuild") {
        matchingBuild({
          delId: this.delId,
          portResblockId: m.portResblockId,
          portType: m.portType,
          type: 0,
          platformResblockId: m.platformResblockId,
          kw,
        }).then(cb).catch(ct);
      } else if (key == "portUnit") {
        matchingUnit({
          delId: this.delId,
          portResblockId: m.portResblockId,
          portType: m.portType,
          portBuildId: m.portBuildId,
          platformResblockId: m.platformResblockId,
          platformBuildId: m.platformBuildId,
          kw,
        }).then(cb).catch(ct);
      } else if (key == "portDoorNum") {
        matchinDoorNum({
          delId: this.delId,
          portResblockId: m.portResblockId,
          portBuildId: m.portBuildId,
          portUnitId: m.portUnitId,
          portType: m.portType,
          platformResblockId: m.platformResblockId,
          platformBuildId: m.platformBuildId,
          platformUnitId: m.platformUnitId,
          kw,
        }).then(cb).catch(ct);
      }
    },

    handleChangeHsh(way, id) {
      const m = this[way]
      // console.log('选中==', { way, id }, this[way].buildUnitDoorOptions);
      let key = "";
      let item = m.buildUnitDoorOptions.find((v) => {
        if (v.platformBuildId == id) {
          key = "platformBuildId";
          return true;
        } else if (v.platformUnitId == id) {
          key = "platformUnitId";
          return true;
        } else if (v.platformDoorNumId == id) {
          key = "platformDoorNumId";
          return true;
        }
      });

      if (key == "platformBuildId") {
        m.portUnit = "";
        m.portUnitId = "";
        m.platformUnitId = "";
        m.portDoorNum = "";
        m.portDoorNumId = "";
        m.platformDoorNumId = "";
      } else if (key == "platformUnitId") {
        m.portDoorNum = "";
        m.portDoorNumId = "";
        m.platformDoorNumId = "";
      }

      Object.assign(m, item);

      const arr = ["portBuild", "portUnit", "portDoorNum"].filter((v) => !!this.portVO[v]);
      if (arr.length >= this.portVO.hallRoomNumber.length) {
        this.verifyBuildSize();
      }
    },

    verifyBuildSize() {
      this.isResetPriceBuildSize = true;
      this.portVO.isMatchingBuild = true;

      matchingBuild({
        delId: this.delId,
        portResblockId: this.portVO.portResblockId,
        portType: this.portVO.portType,
        type: 1,
        platformResblockId: this.portVO.platformResblockId,
        portDoorNumId: this.portVO.portDoorNumId,
        platformDoorNumId: this.portVO.platformDoorNumId,
      }).then((content) => {
        this.portVO.isMatchingBuild = false;
        this.portVO.isCheckingPrice = true;

        let obj = JSON.parse(content);
        if (obj.attr && obj.attr.mianJi && obj.attr.mianJi.value) {
          let buildSize = obj.attr.mianJi.value;
          this.$message.info("当前已帮您匹配到该房源的面积，此时面积不可修改");
          this.myBuildSize = buildSize;
          this.portVO.buildSizeLocked = true;
          this.fetchCheckPrice();
        } else {
          this.portVO.buildSizeLocked = false;
          this.fetchCheckPrice();
        }
        
      }).catch(() => {
        this.portVO.buildSizeLocked = false;
        this.fetchCheckPrice();
      });
    },

    // 获取某小区的户室号栏目数
    getHshColumn(way, info) {
      const m = this[way]
      m.huShiHao = false;
      m.buildUnitDoorOptions = [];

      m.hallRoomLoading = true;
      this.resetHuShiHao(way);

      if (m.hallRoomNumber.length) {
        m.hallRoomNumber = [];
      }

      return matchingBuild({
        delId: this.delId,
        portResblockId: info.portResblockId,
        portType: m.portType,
        type: 1,
        platformResblockId: info.platformResblockId,
      }).then((content) => {
        // 成功查询到
        this.tryTimes = 0;

        m.hallRoomLoading = false;
        if (content == "{}") {
          return;
        }
        let data = JSON.parse(content);

        const keys = ["isShowBuilding", "isShowUnit", "isShowHouse"];
        const arr = hallRoomNumber.filter((item, i) => data[keys[i]] == 1);
        m.hallRoomNumber = arr;

        m.huShiHao = data.huShiHao;
        // console.log("是否支持手动", data.huShiHao);

        // 手动输入则可以开始校验价格了
        if (data.huShiHao) {
          this.portVO.buildSizeLocked = false;
          this.fetchCheckPrice();
        }
        
      }).catch(() => {
        let setSuccess = this.setTimer(() => {
          this.getHshColumn(way, info);
          // console.log("重新匹配几栏。。。");
        });
        if (!setSuccess) {
          m.hallRoomLoading = false;
        }
      });
    },

    // 重试户室号栏目
    handleRetryColumn() {
      this.getHshColumn("portVO", this.portVO);
    },

    resetHuShiHao(way) {
      const m = this[way]
      m.portBuild = "";
      m.portBuildId = "";
      m.portUnit = "";
      m.portUnitId = "";
      m.portDoorNum = "";
      m.portDoorNumId = "";

      m.platformBuildId = "";
      m.platformUnitId = "";
      m.platformDoorNumId = "";

      m.huShiHao = false;
    },

    handlePopShow() {
      this.popVisible = true;

      this.popModel.searchKey = "";
      this.popModel.portResblockName = "";
      this.popModel.platformResblockId = "";
      this.popModel.housingEstateOptions = [];
    },

    handlePopConfirm() {
      if (this.popModel.platformResblockId) {
        this.portVO.portResblockName = this.popModel.portResblockName;
        this.portVO.portResblockId = this.popModel.portResblockId;
        this.portVO.platformResblockId = this.popModel.platformResblockId;

        this.getHshColumn("portVO", this.portVO);
        this.popVisible = false;
        // this.popResblockVisible = false;
      } else {
        if (this.popModel.housingEstateOptions.length) {
          return this.$message.error("请选择弹窗中的选项匹配小区");
        }

        return this.$message.error("请输入小区或关键字后，点击搜索");
      }
    },

    remoteMethod(key) {
      return (query) => {
        if (!query) return;
        this.handleFocusHsh("portVO", key, query);
      };
    },
  },
};
</script>

<style scoped>
.cell {
  border-left: 1px solid #dfe6ec;
  border-top: 1px solid #dfe6ec;
  padding: 5px 10px;
}
.reject-input >>> .el-input__inner {
  border-color: red;
}

</style>
